<template>
  <div>
    <div class="order-setting-item mobile-setting-radius">
      <resourceConfig />
    </div>
    <div class="order-setting-item full-screen mobile-setting-radius" style="margin-top:12px;padding-top:5px;padding-bottom:5px;">
      <fieldTree
        :field-items="fieldItems"
        :default-expanded-keys="defaultExpandedKeys"
        :draggable="true"
        :allow-drop="allowDrop"
        @getData="getData"
        @addField="addField"
        @editField="editField"
        @node-drop="handleDrop" />
    </div>
    <el-dialog
      :visible.sync="fieldDialog"
      :append-to-body="false"
      class="dialog-size-auto small-common-dialog-size setting-dialog"
      width="365px"
      @close="handleClose"
    >
      <div class="main">
        <Title :title="!isEdit?'添加字段':'编辑字段'" font-size="16px" style="margin-bottom:20px;"/>
        <el-form ref="fieldForm" :model="fieldForm" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item label="字段名称" prop="name">
            <el-input v-model="fieldForm.name" maxlength="50" size="small" />
          </el-form-item>
          <el-form-item label="输入方式" prop="inputType">
            <el-select v-model="fieldForm.inputType" placeholder="请选择输入方式" size="small" @change="selInputType">
              <el-option :value="0" label="输入框" />
              <el-option :value="1" label="下拉框" />
            </el-select>
          </el-form-item>
          <div>
            <el-form-item v-if="fieldForm.inputType === 0" label="输入限制" prop="inputLimit">
              <el-select v-model="fieldForm.inputLimit" placeholder="请选择输入限制" size="small">
                <el-option :value="0" label="文本型" />
                <el-option :value="1" label="数值型" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item v-for="(item, index) in fieldForm.options" :key="index" :label="`选项${index+1}`" :rules="rules.label" :prop="`options.${index}.label`">
            <div class="flex-item">
              <el-input v-model="item.label" maxlength="50" size="small" />
              <p class="del" @click="delOption(index)">删除</p>
            </div>
          </el-form-item>
          <div>
            <el-form-item v-if="fieldForm.inputType === 1" class="no-bottom">
              <span class="del" @click="addOptions">添加选项</span>
            </el-form-item>
          </div>
          <el-form-item label="是否必填" prop="required">
            <el-radio v-model="fieldForm.required" :label="1">是</el-radio>
            <el-radio v-model="fieldForm.required" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item v-if="flyPriceSetting" label="" prop="isShowQuery">
            <el-checkbox v-model="fieldForm.isShowQuery">飞来询价展示该字段</el-checkbox>
          </el-form-item>
        </el-form>
        <div class="btn-container">
          <el-button :loading="btnLoading" type="primary" size="small" @click="submit">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import resourceConfig from '@/components/Configuration/resourceConfig';
import fieldTree from '@/components/SettingPage/fieldTree';
import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { editSetting, addSetting, sortPlatFormSetting } from '@/api/setting';

export default {
  components: { resourceConfig, fieldTree, Title },
  props: {
    fieldItems: {
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      fieldDialog: false,
      rules: {
        name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
        inputType: [{ required: true, message: '请选择输入方式', trigger: 'change' }],
        inputLimit: [{ required: true, message: '请选择输入限制', trigger: 'change' }],
        required: [{ required: true, message: '请选择是否必填', trigger: 'change' }],
        label: [{ required: true, message: '请输入选项', trigger: 'blur' }]
      },
      isEdit: false,
      fieldForm: {
        options: []
      },
      btnLoading: false,
      fieldData: {},
      flyPriceFields: ['价格信息', '上刊价格', '更多上刊信息'],
      flyPriceSetting: false
    };
  },
  methods: {
    hasRouteAuth,
    getData(respetPid) {
      this.$emit('getData', respetPid);
    },
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.data.fieldSetting && draggingNode.level === dropNode.level) {
        // 向上拖拽 || 向下拖拽
        if (dropNode.data._isAdd) {
          return false;
        }
        return type === 'prev' || type === 'next';
      } else {
        // 不同级进行处理
        return false;
      }
    },
    async handleDrop(draggingNode, dropNode, dropType, ev) {
      const params = {};
      params.dragId = draggingNode.data.id;
      params.dropId = dropNode.data.id;
      params.dropType = dropType === 'before' ? 0 : 1;
      const res = await sortPlatFormSetting(params);
      if (res.data === 200) {
        this.$emit('getData');
      }
    },
    addField(data) { // 新增字段
      this.fieldData = data;
      if (this.flyPriceFields.includes(data.name)) {
        this.flyPriceSetting = true;
      }
      this.fieldDialog = true;
      this.$set(this.fieldForm, 'required', 1);
    },
    editField(val) { // 编辑字段
      const value = JSON.parse(JSON.stringify(val));
      this.isEdit = true;
      const node = this.getParentNode(value, this.fieldItems.filter(i => i.name === '平台字段配置'));
      if (this.flyPriceFields.includes(node.name)) {
        this.flyPriceSetting = true;
      }
      this.fieldDialog = true;
      this.$set(this.fieldForm, 'id', value.id);
      this.$set(this.fieldForm, 'name', value.name);
      this.$set(this.fieldForm, 'inputLimit', value.inputLimit);
      this.$set(this.fieldForm, 'inputType', value.inputType);
      this.$set(this.fieldForm, 'options', value.options);
      this.$set(this.fieldForm, 'required', value.required);
      this.$set(this.fieldForm, 'orderPlatformId', value.parentId);
      this.$set(this.fieldForm, 'isShowQuery', value.isShowQuery);
      this.fieldForm.pid = value.pid;
    },
    getParentNode(node, tree = []) {
      const result = [];
      const find = (node, tree) => {
        tree.forEach(treeItem => {
          if (treeItem.item && treeItem.item.find(i => i.id === node.id)) {
            result.push(treeItem);
          }
          if (treeItem.item && treeItem.item.length) {
            find(node, treeItem.item);
          }
        });
      };
      find(node, tree);
      return result[0] || {};
    },
    selInputType(val) {
      this.$set(this.fieldForm, 'options', []);
      if (val) {
        this.addOptions();
      }
    },
    addOptions() {
      this.fieldForm.options.push({ value: '', label: '' });
    },
    delOption(index) {
      this.fieldForm.options.splice(index, 1);
    },
    submit() {
      this.$refs.fieldForm.validate(valid => {
        if (valid) {
          if (this.fieldForm.options && this.fieldForm.options.length > 0) {
            this.fieldForm.options.forEach((item, index) => {
              item.value = String(index + 1);
            });
          }
          const params = JSON.parse(JSON.stringify(this.fieldForm));
          params.type = 16;
          params.level = 6;
          // 新增字段
          if (!this.isEdit) {
            params.orderPlatformId = this.fieldData.id;
          }
          if (!params.inputType) {
            delete params.options;
          }
          this.submitField(params);
        } else {
          return false;
        }
      });
    },
    async submitField(params) {
      let res = null;
      if (this.isEdit) {
        res = await editSetting(params);
      } else {
        res = await addSetting(params);
      }
      if (res.code === 200) {
        this.$emit('getData', this.isEdit ? [params.pid] : [this.fieldData.pid]);
      }
      ElMessage.success(res.message);
      this.handleClose();
    },
    handleClose() {
      this.isEdit = false;
      this.fieldDialog = false;
      this.flyPriceSetting = false;
      this.$refs.fieldForm.resetFields();
      this.fieldForm = { options: [] };
    }
  }
};
</script>

<style lang="scss" scoped>
.order-setting-item {
  background-color: #fff;
  padding: 24px;
}
.full-screen {
  min-height: calc(100vh - 180px);
}
.flex-item {
  display: flex;
  align-items: flex-start;
}
.del {
   margin: 0 0 0 10px;
   color: #406Eff;
   cursor: pointer;
}
.btn-container {
  display: flex;
  justify-content: center;
}
.setting-dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 24px 12px 24px 24px !important;
    }
  }
}
.demo-ruleForm {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 12px;

}
.el-form{
  .el-form-item {
    &.no-bottom {
      margin-bottom: 0px;
      .del {
        margin-left: 0;
      }
    }
    ::v-deep .el-input--small,.el-input__inner {
      width: 200px;
    }
  }
}
</style>
